﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HPSocket;
using Confluent.Kafka;
using System.Threading;
using RTUDataAcquisition.DataAccess;
using RTUDataAcquisition.AppCode;
using RTUDataAcquisition.Model;
using System.Runtime.Caching;
using System.Runtime.InteropServices;
using RTUDataAcquisition.Utils.Emails;

namespace RTUDataAcquisition
{
   
public partial class MainForm : Form
    {
        public static HPSocket.Tcp.TcpServer server = new HPSocket.Tcp.TcpServer();
        //public static List<ClientModel> listClient = new List<ClientModel>();
        public static List<EssModel> listEss = new List<EssModel>();
      
        public static DataTable dtAlarmConfig;
        public static DataTable dtDeviceInfo = new DataTable();
        public static DataTable TransDeviceInfo = new DataTable();

        public const int THREADPOOL_MIN_NUM = 1;
        public const int THREADPOOL_MAX_NUM = 1000;// 线程池的最大数，表示RTU同时可以链接的最大数
        /// <summary>
        /// 报文协议头长度
        /// </summary>
        public static int Rtu_header_size = 14;

        /// <summary>
        /// 多包报文协议头长度
        /// </summary>
        public static int Rtu_multi_header_size = 17;

        /// <summary>
        /// 报文最大长度
        /// </summary>
        public static int Rtu_max_size = 2048;

        /// <summary>
        /// 报文起始符
        /// </summary>
        public static byte Rtu_ascii_stx = 0x02;

        /// <summary>
        /// 多包传输正文起始符
        /// </summary>
        public static byte Rtu_ascii_syn = 0x16;

        /// <summary>
        /// 消息队列服务器地址
        /// </summary>
        public static string serverAddr = "";
        //public static string serverAddr = "www.litao.site:9092";

        /// <summary>
        /// 消息队列服务器用户名
        /// </summary>
        public static string serverUser = "";

        /// <summary>
        /// 消息队列服务器用户名密码
        /// </summary>
        public static string serverPassword = "";

        /// <summary>
        /// 消息队列生产者
        /// </summary>
        public static IProducer<int, byte[]> producer;

        /// <summary>
        /// 是否显示信息
        /// </summary>
        public bool showMessage = false;

        /// <summary>
        /// 是否保存数据
        /// </summary>
        public bool saveData = true;


        public MainForm()
        {
            InitializeComponent();
            DateTime dateTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm") + ":00");
        }

        private string GetIPandPort(IntPtr connId)
        {
            string ip = string.Empty;
            ushort port;
            server.GetRemoteAddress(connId, out ip, out port);
            return ip + ":" + port;
        }

        /// <summary>
        /// 设置界面控件相关状态的方法
        /// </summary>
        private void SetControlState()
        {
            txtIPAdress.Enabled = false;
            txtPort.Enabled = false;
            cbxSelect1.SelectedIndex = 0;
        }

        /// <summary>
        /// 初始化HPSocket
        /// </summary>
        private void InitHPSocketServer()
        {
            if (INIConfig.IpAddress.Trim() != "" && INIConfig.IpPort.Trim() != "")
            {
                txtIPAdress.Text = INIConfig.IpAddress.Trim();
                txtPort.Text = INIConfig.IpPort.Trim();
                //绑定事件
                //绑定监听地址前触发
                server.SocketBufferSize = 102400;
                server.OnPrepareListen += Server_OnPrepareListen;
                //客户端连接请求被接受后触发
                server.OnAccept += Server_OnAccept;
                //发送消息后触发
                server.OnSend += Server_OnSend;
                //收到消息后触发
                server.OnReceive += Server_OnReceive;
                //连接关闭后触发（服务端的连接通常是多个，只要某一个连接关闭了都会触发）
                server.OnClose += Server_OnClose;
                //组件停止后触发
                server.OnShutdown += Server_OnShutdown;
                server.Address = INIConfig.IpAddress.Trim();
                server.Port = ushort.Parse(INIConfig.IpPort.Trim());
                server.AcceptSocketCount = Convert.ToUInt32(INIConfig.ClientMaxCount);
                server.MaxConnectionCount = Convert.ToUInt32(INIConfig.ClientMaxCount);
                server.IsMarkSilence = true;
                server.DisconnectSilenceConnections(30 * 1000);//断开超过30秒的静默连接
                if (!server.Start())
                {
                    myButtonCheck1.Checked = false;
                    Messages.ShowMessage(string.Format("服务端启动失败：{0}，{1}", server.ErrorMessage, server.ErrorCode));
                }
                else
                {
                    myButtonCheck1.Checked = true;
                }
            }
            else
            {
                Messages.ShowMessage("未设置服务器IP和端口，请先进行服务器设置！");
            }
        }

        private void InitTimer()
        {
            timer.Interval = INIConfig.TimerInterval * 1000;
            timer.Tick += Timer_Tick;
            timer.Start();
        }
        private void InitTimer1()
        {
            timer1.Interval = 5*60 * 1000;
            timer1.Tick += Timer1_Tick;
            timer1.Start();
        }
        /// <summary>
        /// 加载设备信息
        /// </summary>
        private void InitStationStatus()
        {
            try
            {
                string strSqlCondition = string.Empty;
                if (txtSelect.Text.Trim() != string.Empty)
                {
                    if (cbxSelect1.SelectedIndex == 0)//编号
                    {
                        strSqlCondition = " where StationNo like '%" + txtSelect.Text.Trim() + "%'";
                    }
                    else //名称
                    {
                        strSqlCondition = " where StationName like '%" + txtSelect.Text.Trim() + "%'";
                    }
                }
                DataTable dt = DataBusiness.GetStationStatus(strSqlCondition);
                if (dt != null)
                {
                    dgvDevice.DataSource = dt;
                    tsslDeviceCount.Text = dt != null ? dt.Rows.Count.ToString() : "0";
                    tsslOnline.Text = dt.Select("Status='在线'").Length.ToString();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void InitTransDevice()
        {
            try
            {
                DataTable dt = DataBusiness.GetTransDevice();
                if (dt != null)
                {
                    TransDeviceInfo = dt;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 显示信息
        /// </summary>
        /// <param name="strMsg">信息内容</param>
        public void ShowMessage(string strMsg)
        {
            listMessage.BeginInvoke((MethodInvoker)delegate
            {
                if (showMessage)
                {
                    if (listMessage.Items.Count > 200)
                    {
                        listMessage.Items.RemoveAt(0);
                    }
                    listMessage.Items.Add("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "]  " + strMsg);
                    listMessage.SelectedIndex = listMessage.Items.Count - 1;
                    listMessage.SelectedIndex = -1;
                }
            });
        }

        public void InitDeviceInfo(string strST, string strTime)
        {
            if (dtDeviceInfo != null)
            {
                DataRow[] dr = dtDeviceInfo.Select(string.Format("StationNo='{0}'", strST));
                if (dr.Length > 0)
                {
                    dr[0]["LastTime"] = strTime;
                    dr[0]["Status"] = "在线";
                }
                else
                {
                    DataRow drTemp = dtDeviceInfo.NewRow();
                    drTemp["StationNo"] = strST;
                    drTemp["StationName"] = "";
                    //drTemp["StationType"] = model.TELTYPE;
                    drTemp["LastTime"] = strTime;
                    drTemp["Status"] = "在线";
                    dtDeviceInfo.Rows.Add(drTemp);
                }

                //dgvDevice.BeginInvoke((MethodInvoker)delegate
                //{
                //    dgvDevice.DataSource = dtDeviceInfo;
                //});
            }
        }

        /// <summary>
        /// 创建消息队列生产者
        /// </summary>
        private void CreateProducer()
        {
            var conf = new ProducerConfig
            {
                BootstrapServers = serverAddr
            };
            producer = new ProducerBuilder<int, byte[]>(conf).SetErrorHandler((_, e) => Messages.SaveLog("消息队列生产数据异常:" + e.Reason, ELogLayer.BusinessRule, ELogType.Error)).Build();
        }

        /// <summary>
        /// 创建消息队列数据消费者
        /// </summary>
        /// <returns>Consumer</returns>
        public void CreateConsumerData(object partitionIndex)
        {
            var conf = new ConsumerConfig
            {
                GroupId = INIConfig.GroupData,
                BootstrapServers = serverAddr,
                EnableAutoOffsetStore = false,
                AutoOffsetReset = AutoOffsetReset.Earliest,
                FetchMaxBytes = 1024 * 1024 * 10
            };

            using (var c = new ConsumerBuilder<int, byte[]>(conf)
                .SetErrorHandler((_, e) => Messages.SaveLog("消息队列消费数据异常:" + e.Reason, ELogLayer.BusinessRule, ELogType.Error))
                .Build())
            {
                //c.Subscribe(topicData);
                c.Assign(new TopicPartition(INIConfig.TopicData, new Partition((int)partitionIndex)));
                try
                {
                    while (true)
                    {
                        try
                        {
                            var cr = c.Consume(2000);
                            if (cr != null)
                            {
                                IntPtr connId = (IntPtr)cr.Message.Key;
                                if (cr.Message.Value[10] == 0x33 || cr.Message.Value[10] == 0x32)
                                {
                                    if (ParseData.ParseSL651AddReport(connId, cr.Message.Value))
                                    {
                                        byte[] addr = new byte[5];
                                        Array.Copy(cr.Message.Value, 3, addr, 0, 5);
                                        string strST = TransData.ConvertData(addr);
                                        byte[] time = new byte[5];
                                        Array.Copy(cr.Message.Value, 32, time, 0, 5);
                                        string strTime = TransData.DataToDateString(time);
                                        if (cr.Message.Value[10] == 0x33)
                                        {
                                            ShowMessage(string.Format("处理遥测站:{0}[{1}]加报,消费队列:{2}", strST, strTime, cr.TopicPartitionOffset));
                                        }

                                        if (cr.Message.Value[10] == 0x32)
                                        {
                                            ShowMessage(string.Format("处理遥测站:{0}[{1}]定时报,消费队列:{2}", strST, strTime, cr.TopicPartitionOffset));
                                        }
                                        c.StoreOffset(cr);
                                    }
                                }
                                if (cr.Message.Value[10] == 0x34)
                                {
                                    if (ParseData.ParseSL651HoursReport(connId, cr.Message.Value))
                                    {
                                        byte[] addr = new byte[5];
                                        Array.Copy(cr.Message.Value, 3, addr, 0, 5);
                                        string strST = TransData.ConvertData(addr);
                                        byte[] time = new byte[5];
                                        Array.Copy(cr.Message.Value, 32, time, 0, 5);
                                        string strTime = TransData.DataToDateString(time);
                                        ShowMessage(string.Format("处理遥测站:{0}[{1}]小时报,消费队列:{2}", strST, strTime, cr.TopicPartitionOffset));
                                        c.StoreOffset(cr);
                                    }
                                }
                                if (cr.Message.Value[10] == 0x31)
                                {
                                    if (ParseData.ParseSL651IntervalReport(connId, cr.Message.Value))
                                    {
                                        //byte[] addr = new byte[5];
                                        //Array.Copy(cr.Message.Value, 3, addr, 0, 5);
                                        //string strST = TransData.ConvertData(addr);
                                        //byte[] time = new byte[5];
                                        //Array.Copy(cr.Message.Value, 32, time, 0, 5);
                                        //string strTime = TransData.DataToDateString(time);
                                        //ShowMessage(string.Format("处理遥测站:{0}[{1}]小时报,消费队列:{2}", strST, strTime, cr.TopicPartitionOffset));
                                        c.StoreOffset(cr);
                                    }
                                }
                                //c.StoreOffset(cr);

                                if (saveData)
                                {
                                    string strData = TransData.ConvertDataBySpace(cr.Message.Value);
                                    string strMsg = "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "              " + "(" + GetIPandPort((IntPtr)connId) + ")" + "              " + cr.Message.Value.Length + "B ] \r\n" + strData + "\r\n";
                                    Messages.SaveLog(strMsg, ELogType.Data);
                                }
                            }
                        }
                        catch (ConsumeException e)
                        {
                            Messages.SaveLog("消息队列消费数据异常:" + e.Error.Reason, ELogLayer.BusinessRule, ELogType.Error);
                        }
                    }
                }
                catch (OperationCanceledException e)
                {
                    c.Close();
                    Messages.SaveLog("消息队列消费数据线程异常关闭:" + e.Message, ELogLayer.BusinessRule, ELogType.Error);
                    CreateConsumerData(partitionIndex);
                }
            }
        }

        /// <summary>
        /// 创建消息队列图片数据消费者
        /// </summary>
        /// <returns>Consumer</returns>
        public void CreateConsumerImage(object partitionIndex)
        {
            var conf = new ConsumerConfig
            {
                GroupId = INIConfig.GroupImage,
                BootstrapServers = serverAddr,
                EnableAutoOffsetStore = false,
                AutoOffsetReset = AutoOffsetReset.Earliest,
                FetchMaxBytes = 1024 *1024 * 5
            };
            using (var c = new ConsumerBuilder<int, byte[]>(conf)
                           .SetErrorHandler((_, e) => Messages.SaveLog("消息队列消费图片数据异常:" + e.Reason, ELogLayer.BusinessRule, ELogType.Error))
                           .Build())
            {
                //c.Subscribe(topicImage);
                c.Assign(new TopicPartition(INIConfig.TopicImage, new Partition((int)partitionIndex)));
                try
                {
                    while (true)
                    {
                        try
                        {
                            var cr = c.Consume(2000);
                            if (cr != null)
                            {
                                IntPtr connId = (IntPtr)cr.Message.Key;
                                EssDataModel edm = new EssDataModel();
                                if (ParseData.ParseSL651PictureReport(connId, cr.Message.Value, ref edm))
                                {
                                    ShowMessage(string.Format("处理遥测站:{0}[{1}]图片报({3}/{4}),消费队列:{2}", edm.ST, edm.TT, cr.TopicPartitionOffset, edm.CurrentPackage, edm.TotalPackages));
                                    if (saveData)
                                    {
                                        string strData = TransData.ConvertDataBySpace(cr.Message.Value);
                                        string strMsg = "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "              " + "(" + GetIPandPort((IntPtr)connId) + ")" + "              " + cr.Message.Value.Length + "B ] \r\n" + strData + "\r\n";
                                        Messages.SaveLog(strMsg, ELogType.Data);
                                    }
                                }
                                c.StoreOffset(cr);
                            }
                        }
                        catch (ConsumeException e)
                        {
                            Messages.SaveLog("消息队列消费图片数据异常:" + e.Error.Reason, ELogLayer.BusinessRule, ELogType.Error);
                        }
                    }
                }
                catch (OperationCanceledException e)
                {
                    c.Close();
                    Messages.SaveLog("消息队列消费图片线程异常关闭:" + e.Message, ELogLayer.BusinessRule, ELogType.Error);
                    CreateConsumerImage(partitionIndex);
                }
            }
        }
        /// <summary>
        /// 数据回包
        /// </summary>
        /// <param name="connId"></param>
        /// <param name="byteData"></param>
        public void packResp(IntPtr connId, byte[] byteData)
        {
            List<byte> listSend = new List<byte>();
            listSend.Add(0x7E);
            listSend.Add(0x7E);
            listSend.Add(byteData[3]);
            listSend.Add(byteData[4]);
            listSend.Add(byteData[5]);
            listSend.Add(byteData[6]);
            listSend.Add(byteData[7]);
            listSend.Add(byteData[2]);
            listSend.Add(byteData[8]);
            listSend.Add(byteData[9]);
            listSend.Add(byteData[10]);
            listSend.Add(0x80);
            listSend.Add(0x08);
            listSend.Add(0x02);
            //listSend.AddRange(byteSerial);
            listSend.Add(byteData[11]);
            listSend.Add(byteData[12]);
            listSend.AddRange(TransData.ConvertHexStringToBytes(DateTime.Now.ToString("yyyyMMddHHmmss").Substring(2)));
            listSend.Add(0x04);
            int crc = TransData.CRC16(listSend.ToArray(), listSend.Count);   //对数据进行CRC校验
            listSend.Add((byte)(crc >> 8));
            listSend.Add((byte)(crc >> 0));
            //if (byteData[3] == 0x90 && byteData[6]==0x00 && byteData[7] == 0x90)
            //{
            //    Messages.SaveLog(string.Format("回包遥测站:{0}[{1}]加报", TransData.ConvertData(listSend.ToArray()), DateTime.Now.ToString("yyyyMMddHHmmss")));
            //}
            //Messages.SaveLog(string.Format("回包遥测站:{0}[{1}]加报", byteData[3]+ byteData[4]+ byteData[5]+ byteData[6]+ byteData[7], DateTime.Now.ToString("yyyyMMddHHmmss")));
            server.Send(connId, listSend.ToArray(), listSend.Count);

           
        }

        public void sendProd(IntPtr connId, byte[] byteData,string Topic)
        {
            Message<int, byte[]> msg = new Message<int, byte[]>();
            msg.Key = (int)connId;
            msg.Value = byteData;
            producer.Produce(Topic, msg);
        }

        /// <summary>
        /// 图片回包
        /// </summary>
        /// <param name="connId"></param>
        /// <param name="byteData"></param>
        public void packRespImg(IntPtr connId, byte[] byteData)
        {
            if (byteData.Length % 1044 == 0 && byteData.Length >= 1044)
            {
                int count = (int)byteData.Length / 1044;
                for (int i = 0; i < count; i++)
                {
                    int offset = i * 1044;
                    if (int.Parse(byteData[16 + offset].ToString()) == ((byteData[15 + offset] >> 4) + (byteData[14 + offset] << 4)))
                    {
                        packResp(connId, byteData);
                    }
                }
            }
            if (byteData.Length < 1044)
            {
                packResp(connId, byteData);
            }
        }
        public class entityIdData
        {
            public IntPtr m_connId;
            public byte[] m_data;
            public entityIdData(IntPtr connId, byte[] data)
            {
                m_connId = connId;
                m_data = data;
            }
            public IntPtr getconnId() { return m_connId; }
            public byte[] getdata() { return m_data; }
        }
        public void ParseSL651(object entity)
        {
            try
            {
                entityIdData myObj = entity as entityIdData;
                IntPtr connId = myObj.getconnId();
                byte[] byteData = myObj.getdata();
                if (byteData == null || byteData.Length == 0)
                {
                    return ;
                }
                //判断数据包长度是否过小，最小的数据包长度为链路维持报
                if (byteData.Length < Rtu_header_size + 8)
                {
                    return ;
                }

                if (byteData[10] != 0x36)
                {
                    packResp(connId, byteData);
                    sendProd(connId, byteData, INIConfig.TopicData);
                    if (byteData[3] == 0x90 && byteData[6] == 0x00 && byteData[7] == 0x90)
                    {
                        TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                        Messages.SaveLog(string.Format("记录数据时间戳：{0}", Convert.ToInt64(ts.TotalMilliseconds).ToString()));
                    }
                }
                else
                {
                    //图片
                    sendProd(connId, byteData, INIConfig.TopicImage);
                    packRespImg(connId, byteData);
                    if (byteData[3] == 0x90 && byteData[6] == 0x00 && byteData[7] == 0x90)
                    {
                        TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                        Messages.SaveLog(string.Format("记录图片时间戳：{0}", Convert.ToInt64(ts.TotalMilliseconds).ToString()));
                    }
                }
                //Messages.SaveLog("接收111客户端数据:" + byteData[10]);
                return ;
            }
            catch (Exception ex)
            {
                //Messages.SaveLog(ex + "\r\n数据内容:" + TransData.ConvertData(byteData), ELogLayer.BusinessRule, ELogType.Error);
                return ;
            }
        }
            /// <summary>
            /// 解析遥测站数据
            /// </summary>
            /// <param name="connId">客户端连接ID</param>
            /// <param name="byteData">数据</param>
            /// <returns>true,false</returns>
            public bool ParseSL651s(IntPtr connId, byte[] byteData)
        {
            try
            {
                if (byteData == null || byteData.Length == 0)
                {
                    return false;
                }
                int intDataLength = 0;//报文正文数据长度
                int intLength = 0;//报文正文数据长度

                //判断数据包长度是否过小，最小的数据包长度为链路维持报
                if (byteData.Length < Rtu_header_size + 8)
                {
                    return false;
                }
                //20240124
                if (byteData[10] == 0x36)
                {
                    byte[] addr_img = new byte[5];
                    byte[] pwd_img = new byte[2];
                    int byte_length = byteData.Length; //总长度
                    Array.Copy(byteData, 3, addr_img, 0, 5);
                    Array.Copy(byteData, 8, pwd_img, 0, 2);
                    string strST_img = TransData.ConvertData(addr_img);
                    string strpwd_img = TransData.ConvertData(pwd_img);
                    string btye_index = "7E7E00" + strST_img + strpwd_img; //报文索引
                    string btyestr = TransData.ConvertData(byteData);
                    int countNum = Count(btyestr, btye_index); //报文索引出现的次数
                    IEnumerable<int> indexList = FindIndex(btyestr, btye_index);
                    //是否粘包
                    //拆包
                    if (countNum > 1)
                    {
                        List<int> subIndex = new List<int>();
                        foreach (var item in indexList)
                        {
                            subIndex.Add(item);
                        }

                        for (int i = 0; i < subIndex.Count(); i++)
                        {
                            string btye_str = "";
                            byte[] byteData_img = new byte[0];
                            if (i + 1 < subIndex.Count())
                            {
                                btye_str = btyestr.Substring(subIndex[i], subIndex[i + 1] - subIndex[i]);
                            }
                            else
                            {
                                btye_str = btyestr.Substring(subIndex[i], btyestr.Length - subIndex[i]);
                            }
                            byteData_img = TransData.ConvertHexStringToBytes(btye_str);
                            //检查报文最大长度
                            if (byteData_img.Length > Rtu_max_size)
                            {
                                Messages.SaveLog("检查报文最大长度出错byteData_img.Length=" + byteData_img.Length + "/Rtu_max_size=" + Rtu_max_size);
                                return false;
                            }

                            //检查帧头
                            if (byteData_img[0] != 0x7E || byteData_img[1] != 0x7E)
                            {
                                Messages.SaveLog("检查帧头出错");
                                return false;
                            }

                            int crc1_img = TransData.CRC16(byteData_img, byteData_img.Length - 2);   //对数据进行CRC校验
                            int crc2_img = byteData_img[byteData_img.Length - 2] << 8 | byteData_img[byteData_img.Length - 1];
                            if (crc1_img != crc2_img)   //CRC校验错误
                            {
                                Messages.SaveLog("crc校验出错==" + TransData.ConvertData(byteData_img));
                                return false;
                            }
                            //检查遥测站加报报功能码
                            if (byteData_img[10] != 0x33 && byteData_img[10] != 0x36 && byteData_img[10] != 0x32 && byteData_img[10] != 0x31 && byteData_img[10] != 0x34)
                            {
                                Messages.SaveLog("检查遥测站加报报功能码出错==" + TransData.ConvertData(byteData_img));
                                return false;
                            }

                            //检查上行下行标识符
                            int idex_img = byteData_img[11] & 0xf0;
                            if (idex_img != 0)
                            {
                                Messages.SaveLog("检查上行下行标识符出错==" + TransData.ConvertData(byteData_img));
                                return false;
                            }

                            //检查报文起始符号
                            if (byteData_img[13] != Rtu_ascii_stx && byteData_img[13] != Rtu_ascii_syn)
                            {
                                Messages.SaveLog("检查报文起始符号出错==" + TransData.ConvertData(byteData_img));
                                return false;
                            }

                            //报文起始符号单包
                            if (byteData_img[13] == Rtu_ascii_stx)
                            {
                                intDataLength = byteData_img.Length - 2 - 1 - Rtu_header_size;
                                //单包最小报文正文长度8B
                                if (intDataLength < 8)
                                {
                                    Messages.SaveLog("报文起始符号单包出错，单包最小报文正文长度8B==" + TransData.ConvertData(byteData_img));
                                    return false;
                                }
                            }
                            if (byteData_img[13] == Rtu_ascii_syn)
                            {
                                //多包数据
                                intDataLength = byteData_img.Length - Rtu_multi_header_size;
                                //多包最小报文正文长度4B(其中3B的包总数及序列号，至少1B的正文)
                                if (intDataLength < 4)
                                {
                                    Messages.SaveLog("多包最小报文正文长度4B(其中3B的包总数及序列号，至少1B的正文==" + TransData.ConvertData(byteData_img));
                                    return false;
                                }
                            }

                            intLength = TransData.ConvertNum(byteData_img[11], byteData_img[12]);
                            if (intDataLength != intLength)
                            {
                                Messages.SaveLog("报文长度和报文内的长度不一致==" + TransData.ConvertData(byteData_img));
                                return false;
                            }

                            if (intLength < 23)//检验正文结构长度
                            {
                                Messages.SaveLog("检验正文结构长度<23==" + TransData.ConvertData(byteData_img));
                                return false;
                            }

                            int totalPackages = 0;
                            int indexPackages = 0;
                            byte[] byteSerial = new byte[2];
                            byte[] byteEssData1;//图片头数据
                            byte[] bytePackage = new byte[3];
                            Array.Copy(byteData, 14, bytePackage, 0, 3);
                            TransData.GetTotalPackageAndSerialNumber(bytePackage, ref totalPackages, ref indexPackages);
                            ClientModel cm = MainForm.server.GetExtra<ClientModel>(connId);
                            if (cm != null)
                            {
                                intLength = TransData.ConvertNum(byteData[11], byteData[12]);
                                if (indexPackages == 1)//第一包数据
                                {
                                    byteEssData1 = new byte[intLength];
                                    Array.Copy(byteData, MainForm.Rtu_header_size, byteEssData1, 0, intLength);
                                    Array.Copy(byteEssData1, 3, byteSerial, 0, 2);
                                }
                                //当前包号是否存在
                                if (!cm.ImagePackIndex.PackIndex.Contains(indexPackages))
                                {
                                    cm.ImagePackIndex.PackIndex.Add(indexPackages);
                                }
                                if (totalPackages == indexPackages && totalPackages == cm.ImagePackIndex.PackIndex.Count)//最后一包
                                {
                                    byte[] byteDataSub = new byte[12];
                                    Array.Copy(byteData, 0, byteDataSub, 0, 12);
                                    ImageResponse(connId, addr_img, byteDataSub, bytePackage, byteSerial);
                                    cm.ImagePackIndex = new PackModel();
                                }
                                ShowMessage(string.Format("接收遥测站:{0}图片报({1}/{2})", strST_img, indexPackages, totalPackages));
                                Message<int, byte[]> msg = new Message<int, byte[]>();
                                msg.Key = (int)connId;
                                msg.Value = byteData;
                                producer.Produce(INIConfig.TopicImage, msg);
                            }
                            else
                            {
                                Messages.SaveLog("连接不存在;connid" + Marshal.PtrToStringAnsi(connId));
                            }
                        }
                        return true;
                    }
                }
                //检查报文最大长度
                if (byteData.Length > Rtu_max_size && byteData[10] != 0x99)
                {
                    Messages.SaveLog("检查报文最大长度出错byteData_img.Length=" + byteData.Length + "/Rtu_max_size=" + Rtu_max_size);
                    return false;
                }

                //检查帧头
                if (byteData[0] != 0x7E || byteData[1] != 0x7E)
                {
                    Messages.SaveLog("检查帧头出错");
                    return false;
                }

                int crc1 = TransData.CRC16(byteData, byteData.Length - 2);   //对数据进行CRC校验
                int crc2 = byteData[byteData.Length - 2] << 8 | byteData[byteData.Length - 1];
                if (crc1 != crc2)   //CRC校验错误
                {
                    Messages.SaveLog("CRC校验错误");
                    return false;
                }

                //检查遥测站加报报功能码
                if (byteData[10] != 0x33 && byteData[10] != 0x36 && byteData[10] != 0x32 && byteData[10] != 0x31 && byteData[10] != 0x34 && byteData[10] != 0x99)
                {
                    Messages.SaveLog("检查遥测站加报报功能码错误");
                    return false;
                }

                //检查上行下行标识符
                int idex = byteData[11] & 0xf0;
                if (idex != 0)
                {
                    Messages.SaveLog("上行下行标识符错误");
                    return false;
                }

                //检查报文起始符号
                if (byteData[13] != Rtu_ascii_stx && byteData[13] != Rtu_ascii_syn)
                {
                    Messages.SaveLog("检查报文起始符号错误");
                    return false;
                }

                //报文起始符号单包
                if (byteData[13] == Rtu_ascii_stx)
                {
                    intDataLength = byteData.Length - 2 - 1 - Rtu_header_size;
                    //单包最小报文正文长度8B
                    if (intDataLength < 8)
                    {
                        Messages.SaveLog("单包最小报文正文长度8B错误");
                        return false;
                    }
                }

                if (byteData[13] == Rtu_ascii_syn)
                {
                    //多包数据
                    intDataLength = byteData.Length - Rtu_multi_header_size;
                    //多包最小报文正文长度4B(其中3B的包总数及序列号，至少1B的正文)
                    if (intDataLength < 4)
                    {
                        Messages.SaveLog("多包最小报文正文长度4B错误");
                        return false;
                    }
                }

                intLength = TransData.ConvertNum(byteData[11], byteData[12]);
                if (intDataLength != intLength)
                {
                    Messages.SaveLog("intDataLength="+ intDataLength+ ";intDataLength=" + intDataLength);
                    return false;
                }

                if (intLength < 23)//检验正文结构长度
                {
                    Messages.SaveLog("检验正文结构长度错误");
                    return false;
                }

                byte[] addr = new byte[5];
                Array.Copy(byteData, 3, addr, 0, 5);
                string strST = TransData.ConvertData(addr);

                byte[] time = new byte[5];
                Array.Copy(byteData, 32, time, 0, 5);
                string strTime = TransData.DataToDateString(time);

                //遥测站加报报
                if (byteData[10] == 0x33 || byteData[10] == 0x32 || byteData[10] == 0x31 || byteData[10] == 0x34
                    || byteData[10] == 0x99)
                {
                    if (byteData[10] == 0x33)
                    {
                        ShowMessage(string.Format("接收遥测站:{0}[{1}]加报", strST, strTime));
                    }

                    if (byteData[10] == 0x32)
                    {
                        ShowMessage(string.Format("接收遥测站:{0}[{1}]定时报", strST, strTime));
                    }

                    if (byteData[10] == 0x34)
                    {
                        ShowMessage(string.Format("接收遥测站:{0}[{1}]小时报", strST, strTime));
                    }

                    if (byteData[10] == 0x99)
                    {
                        ShowMessage(string.Format("接收遥测站:{0}[{1}]缆道小车", strST, strTime));
                    }

                    Messages.SaveLog(string.Format("入队遥测站:{0}[{1}]加报", strST, strTime));
                    Message<int, byte[]> msg = new Message<int, byte[]>();
                    msg.Key = (int)connId;
                    msg.Value = byteData;
                    producer.Produce(INIConfig.TopicData, msg);
          
                     
                    var obj = MainForm.server.GetExtra<ClientModel>(connId);
                    if (obj != null)//判断当前链接是否存在
                    {
                        intLength = TransData.ConvertNum(byteData[11], byteData[12]);
                        byte[] byteEssData1 = new byte[intLength];
                        Array.Copy(byteData, MainForm.Rtu_header_size, byteEssData1, 0, intLength);
                        byte[] byteSerial = new byte[2];
                        Array.Copy(byteEssData1, 0, byteSerial, 0, 2);
                        List<byte> listSend = new List<byte>();
                        listSend.Add(0x7E);
                        listSend.Add(0x7E);
                        listSend.AddRange(addr);
                        listSend.Add(byteData[2]);
                        listSend.Add(byteData[8]);
                        listSend.Add(byteData[9]);
                        listSend.Add(byteData[10]);
                        listSend.Add(0x80);
                        listSend.Add(0x08);
                        listSend.Add(0x02);
                        listSend.AddRange(byteSerial);
                        listSend.AddRange(TransData.ConvertHexStringToBytes(DateTime.Now.ToString("yyyyMMddHHmmss").Substring(2)));
                        listSend.Add(0x04);
                        int crc = TransData.CRC16(listSend.ToArray(), listSend.Count);   //对数据进行CRC校验
                        listSend.Add((byte)(crc >> 8));
                        listSend.Add((byte)(crc >> 0));
                        Messages.SaveLog(string.Format("回包遥测站:{0}[{1}]加报", strST, strTime));
                        server.Send(connId, listSend.ToArray(), listSend.Count);
                        //ClientModel cm1 = listClient.Find(t => t.ClientId == connId.ToString());
                        //listClient.Remove(cm1);
                    }
                }
                //遥测站图片报
                if (byteData[10] == 0x36)
                {
                    int totalPackages = 0;
                    int indexPackages = 0;
                    byte[] byteSerial = new byte[2];
                    byte[] byteEssData1;//图片头数据
                    byte[] bytePackage = new byte[3];
                    Array.Copy(byteData, 14, bytePackage, 0, 3);
                    TransData.GetTotalPackageAndSerialNumber(bytePackage, ref totalPackages, ref indexPackages);
                    ClientModel cm = MainForm.server.GetExtra<ClientModel>(connId);
                    if (cm != null) {
                        intLength = TransData.ConvertNum(byteData[11], byteData[12]);
                        if (indexPackages == 1)//第一包数据
                        {
                            byteEssData1 = new byte[intLength];
                            Array.Copy(byteData, MainForm.Rtu_header_size, byteEssData1, 0, intLength);
                            Array.Copy(byteEssData1, 3, byteSerial, 0, 2);
                        }
                        //当前包号是否存在
                        if (!cm.ImagePackIndex.PackIndex .Contains(indexPackages))
                        {
                            cm.ImagePackIndex.PackIndex.Add(indexPackages);
                        }
                        if (totalPackages == indexPackages && totalPackages == cm.ImagePackIndex.PackIndex.Count)//最后一包
                        {
                            byte[] byteDataSub = new byte[12];
                            Array.Copy(byteData, 0, byteDataSub, 0, 12);
                            ImageResponse(connId, addr, byteDataSub, bytePackage, byteSerial);
                            cm.ImagePackIndex = new PackModel();
                        }
                        ShowMessage(string.Format("接收遥测站:{0}图片报({1}/{2})", strST, indexPackages, totalPackages));
                        Message<int, byte[]> msg = new Message<int, byte[]>();
                        msg.Key = (int)connId;
                        msg.Value = byteData;
                        producer.Produce(INIConfig.TopicImage, msg);
                    }
                    else
                    {
                        Messages.SaveLog(Marshal.PtrToStringAnsi(connId));
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Messages.SaveLog(ex + "\r\n数据内容:" + TransData.ConvertData(byteData), ELogLayer.BusinessRule, ELogType.Error);
                return false;
            }
        }
        public static void ImageResponse(IntPtr connId, byte[] addr, byte[] byteData, byte[] bytePackage, byte[] byteSerial)
        {
            var obj = MainForm.server.GetExtra<ClientModel>(connId);
            if (obj != null)//判断当前链接是否存在
            {
                List<byte> listSend = new List<byte>();
                listSend.Add(0x7E);
                listSend.Add(0x7E);
                listSend.AddRange(addr);
                listSend.Add(byteData[2]);
                listSend.Add(byteData[8]);
                listSend.Add(byteData[9]);
                listSend.Add(byteData[10]);
                listSend.Add(0x80);
                listSend.Add(0x08);
                listSend.Add(MainForm.Rtu_ascii_syn);
                listSend.AddRange(bytePackage);
                listSend.AddRange(byteSerial);
                listSend.AddRange(TransData.ConvertHexStringToBytes(DateTime.Now.ToString("yyyyMMddHHmmss").Substring(2)));
                listSend.Add(0x04);
                int crc = TransData.CRC16(listSend.ToArray(), listSend.Count);   //对数据进行CRC校验
                listSend.Add((byte)(crc >> 8));
                listSend.Add((byte)(crc >> 0));
                //Task.Run(async () =>
                //{
                //    try
                //    {
                //        await Task.Delay(1000);
                //        bool x = MainForm.server.Send(connId, listSend.ToArray(), listSend.Count);
                //        Messages.SaveLog($"发送:{x}" + TransData.ConvertData(byteData), ELogLayer.BusinessRule, ELogType.Info);
                //    }
                //    catch (Exception ex)
                //    {
                //        Messages.SaveLog($"发送失败:" + ex.Message, ELogLayer.BusinessRule, ELogType.Error);
                //    }
                //});
                Thread.Sleep(50);
                bool x = MainForm.server.Send(connId, listSend.ToArray(), listSend.Count);
                Messages.SaveLog($"发送:{x}" + TransData.ConvertData(byteData), ELogLayer.BusinessRule, ELogType.Info);

            }

        }

        public static IEnumerable<int> FindIndex(string text, string word)
        {
            if (text.Length < 1 || word.Length < 1)
            {
                yield break;
            }
            int index = 0 - word.Length;
            while ((index = text.IndexOf(word, index + word.Length)) > -1)
            {
                yield return (index);
            }
            yield break;
        }
        public static int Count(string str_big, string str_small)
        {
            int count = 0;//定义次数
            string str_replace = "";//定义代替字符串
            if (str_big.Contains(str_small))//小字符串出现在大字符串中
            {
                //将大字符串中出现的小字符串替换为空串并重新赋给代替字符串
                str_replace = str_big.Replace(str_small, "");
            }
            //大字符串的字符串长度减去代替字符串的长度就等于小字符串中的字符出现在大字符串中的次数
            int char_count = str_big.Length - str_replace.Length;
            //而小字符串所有字符出现在大字符串中的次数应该等于小字符串中字符出现的次数除以小字符串的长度
            count = char_count / str_small.Length;
            return count;//返回次数
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                this.StartPosition = FormStartPosition.CenterScreen;
                INIConfig.LoadSettings();
                HeartCheckTimer.Register(INIConfig.HealthCheckIP, INIConfig.HealthCheckPort, INIConfig.HealthCheckKey, INIConfig.HealthCheckInterval);
                //Messages.SaveLog("开始时间="+ DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ELogLayer.UI, ELogType.Error);
                //////写库
                //DataBusiness.CreateDataBase(INIConfig.DBName + DateTime.Now.Year);
                //DataBusiness.CreateDataBase(INIConfig.RealDataDBName);
                //DataBusiness.CreateHisDataTable("RealData", INIConfig.StrRealdataConn);
                ////读库
                //DataBusiness.CreateDataBase_R(INIConfig.RealDataDBName_R);
                //DataBusiness.CreateDataBase_R(INIConfig.DBName_R + DateTime.Now.Year);
                //DataBusiness.CreateHisDataTable("RealData", INIConfig.StrRealdataConn_R);
                //Messages.SaveLog("检查库时间=" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ELogLayer.UI, ELogType.Error);
                txtIPAdress.Text = INIConfig.IpAddress;
                txtPort.Text = INIConfig.IpPort;
                serverAddr = INIConfig.KafkaAddress;

                //listEss = TransData.GetList<EssModel>(DataBusiness.GetEssConfig());
                SetControlState();
                CreateProducer();
                InitHPSocketServer();
                InitTimer();
                InitTimer1();
                InitStationStatus();
                InitTransDevice();

                //for (int i = 0; i < INIConfig.TopicPartitionData; i++)
                //{
                //    Thread th1 = new Thread(CreateConsumerData);
                //    th1.IsBackground = true;
                //    th1.Start(i);
                //}

                //for (int i = 0; i < INIConfig.TopicPartitionImage; i++)
                //{
                //    Thread th2 = new Thread(CreateConsumerImage);
                //    th2.IsBackground = true;
                //    th2.Start(i);
                //}
            }
            catch (Exception ex)
            {
                Messages.SaveLog(ex, ELogLayer.UI, ELogType.Error);
            }
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            try
            {
                if (DateTime.Now.DayOfYear == 365)
                {
                    DataBusiness.CreateDataBase(INIConfig.DBName + DateTime.Now.AddYears(1).Year);
                    DataBusiness.CreateDataBase_R(INIConfig.DBName_R + DateTime.Now.AddYears(1).Year);
                }

                dgvDevice.BeginInvoke((MethodInvoker)delegate
                {
                    InitStationStatus();
                });
            }
            catch (Exception ex)
            {
                Messages.SaveLog(ex, ELogLayer.UI, ELogType.Error);
            }
        }
        private void Timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                InitTransDevice();
            }
            catch (Exception ex)
            {
                Messages.SaveLog(ex, ELogLayer.UI, ELogType.Error);
            }
        }
        private HandleResult Server_OnShutdown(IServer sender)
        {
            Messages.SaveLog("服务端停止", ELogLayer.UI, ELogType.Info);
            return HandleResult.Ok;
        }

        private HandleResult Server_OnClose(IServer sender, IntPtr connId, SocketOperation socketOperation, int errorCode)
        {
            try
            {
                var obj = server.GetExtra<ClientModel>(connId);
                if (obj != null)//判断当前链接是否存在
                {
                    server.RemoveExtra(connId);
                }

                this.BeginInvoke((MethodInvoker)delegate
                {
                    tsslDeviceClient.Text = server.GetAllExtra().Count.ToString();//(server.ConnectionCount - 1).ToString();
                });
                return HandleResult.Ok;
            }
            catch (Exception ex)
            {
                Messages.SaveLog(string.Format("客户端断开连接错误:{0} 客户端连接数量{1},当前连接ID:{2}", ex.Message, server.GetAllExtra().Count.ToString(), connId.ToString()), ELogLayer.BusinessRule, ELogType.Error);
                return HandleResult.Error;
            }
        }

    
        private HandleResult Server_OnReceive(IServer sender, IntPtr connId, byte[] data)
        {
            try
            {
                //Messages.SaveLog(string.Format("接收：{0} ，数据：{1}", GetIPandPort(connId), TransData.ConvertData(data)), ELogLayer.UI, ELogType.Info);
                entityIdData entity = new entityIdData(connId, data);
                ThreadPool.QueueUserWorkItem(new WaitCallback(ParseSL651), (object)entity);
                //if (!ParseSL651(connId, data))
                //{
                //    Messages.SaveLog("解析数据错误,数据内容:" + TransData.ConvertData(data), ELogLayer.BusinessRule, ELogType.Error);
                //    //server.Disconnect(connId);
                //}
                return HandleResult.Ok;
            }
            catch (Exception ex)
            {
                Messages.SaveLog(string.Format("接收客户端数据错误:{0}", ex.Message), ELogLayer.BusinessRule, ELogType.Error);
                return HandleResult.Error;
            }
        }

        private HandleResult Server_OnSend(IServer sender, IntPtr connId, byte[] data)
        {
            //Messages.SaveLog(string.Format("向连接：{0} 发送成功，长度：{1}", GetIPandPort(connId), data.Length), ELogLayer.UI, ELogType.Info);
            return HandleResult.Ok;
        }

        private HandleResult Server_OnAccept(IServer sender, IntPtr connId, IntPtr client)
        {
            try
            {
                Messages.SaveLog(string.Format("接受客户端连接{0}：{1}", connId, GetIPandPort(connId)), ELogLayer.UI, ELogType.Info);
                var obj = server.GetExtra<ClientModel>(connId);
                if (obj == null)//判断当前链接是否存在
                { 
           
                    ClientModel cm = new ClientModel();
                    cm.DataModel = new EssDataModel();
                    cm.ImagePackIndex = new PackModel();
                    cm.ClientId = connId.ToString();
                    //listClient.Add(cm); 
                    //存储分包对象信息
                    server.SetExtra(connId, cm);
                }
                this.BeginInvoke((MethodInvoker)delegate
                {
                    tsslDeviceClient.Text = server.GetAllExtra().Count.ToString();//server.ConnectionCount.ToString();
                });
                return HandleResult.Ok;
            }
            catch (Exception ex)
            {
                Messages.SaveLog("接受客户端连接错误:" + ex.Message, ELogLayer.BusinessRule, ELogType.Error);
                return HandleResult.Error;
            }
        }

        private HandleResult Server_OnPrepareListen(IServer sender, IntPtr listen)
        {
            Messages.SaveLog("开始监听", ELogLayer.UI, ELogType.Info);
            return HandleResult.Ok;
        }

        /// <summary>
        /// 关闭窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Hide();
            this.notifyIcon.Visible = true;
            e.Cancel = true;
        }

        private void dgvDevice_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, dgvDevice.RowHeadersWidth, e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), dgvDevice.RowHeadersDefaultCellStyle.Font, rectangle, dgvDevice.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter);
        }

        private void myButtonCheck1_Click(object sender, EventArgs e)
        {
            try
            {
                if (myButtonCheck1.Checked)
                {
                    InitHPSocketServer();
                    Messages.SaveLog("开启监控", ELogLayer.UI, ELogType.Info);
                }
                else
                {
                    if (server.HasStarted)
                    {
                        server.Stop();
                        Messages.SaveLog("关闭监控", ELogLayer.UI, ELogType.Info);
                    }
                }
            }
            catch (Exception ex)
            {
                Messages.SaveLog(ex, ELogLayer.UI, ELogType.Info);
            }
        }

        /// <summary>
        /// 搜索
        /// </summary>
        private void btnSelect_Click(object sender, EventArgs e)
        {
            try
            {
                InitStationStatus();
                if (dgvDevice.Rows.Count == 0)
                {
                    Messages.ShowMessage("搜索无相关站点数据!");
                }
            }
            catch (Exception ex)
            {
                Messages.SaveLog(ex, ELogLayer.UI, ELogType.Info);
            }
        }

        private void dgvDevice_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.ColumnIndex == 0 && e.RowIndex >= 0)
                {
                    EssShow essShow = new EssShow(dgvDevice.Rows[e.RowIndex].Cells[1].Value.ToString(), dgvDevice.Rows[e.RowIndex].Cells[2].Value.ToString(), dgvDevice.Rows[e.RowIndex].Cells[3].Value.ToString());
                    essShow.StartPosition = FormStartPosition.CenterScreen;
                    essShow.Show();
                }
            }
            catch (Exception ex)
            {
                Messages.SaveLog(ex, ELogLayer.UI, ELogType.Info);
            }
        }

        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
            }
        }

        private void showMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.Activate();
        }

        /// <summary>
        /// 退出
        /// </summary>
        private void exitMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要退出程序？", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                return;
            }

            if (server.HasStarted)
            {
                server.Stop();
                server.Dispose();
            }

            if (timer.Enabled)
            {
                timer.Stop();
                timer.Dispose();
            }
            if (timer1.Enabled)
            {
                timer1.Stop();
                timer1.Dispose();
            }
            Messages.SaveLog("关闭程序", ELogLayer.UI, ELogType.Info);
            this.Close();
            this.Dispose();
            Application.Exit();
            Application.ExitThread();
            System.Environment.Exit(0);
        }

        private void notifyIcon_DoubleClick(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal)
            {
                this.WindowState = FormWindowState.Minimized;
                this.Hide();
            }
            else if (this.WindowState == FormWindowState.Minimized)
            {
                this.Show();
                this.WindowState = FormWindowState.Normal;
                this.Activate();
            }
        }

        /// <summary>
        /// 设备管理
        /// </summary>
        private void ToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            try
            {
                StationConfig sc = new StationConfig();
                sc.StartPosition = FormStartPosition.CenterScreen;
                sc.Show();
            }
            catch (Exception ex)
            {
                Messages.SaveLog(ex, ELogLayer.UI, ELogType.Info);
            }
        }

        /// <summary>
        /// 服务器设置
        /// </summary>
        private void ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            try
            {
                ServerSetting ss = new ServerSetting();
                ss.StartPosition = FormStartPosition.CenterScreen;
                ss.Show();
            }
            catch (Exception ex)
            {
                Messages.SaveLog(ex, ELogLayer.UI, ELogType.Info);
            }
        }

        /// <summary>
        /// 数据库设置
        /// </summary>
        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            try
            {
                DataBaseSetting dbs = new DataBaseSetting();
                dbs.StartPosition = FormStartPosition.CenterScreen;
                dbs.Show();
            }
            catch (Exception ex)
            {
                Messages.SaveLog(ex, ELogLayer.UI, ELogType.Info);
            }
        }

        /// <summary>
        /// 清空信息
        /// </summary>
        private void tsmiClear_Click(object sender, EventArgs e)
        {
            listMessage.Items.Clear();
        }

        /// <summary>
        ///开启或关闭信息
        /// </summary>
        private void tsmiShow_Click(object sender, EventArgs e)
        {
            showMessage = !showMessage;
            if (showMessage)
            {
                tsmiShow.Text = "关闭信息";
            }
            else
            {
                tsmiShow.Text = "开启信息";
            }
        }

        /// <summary>
        ///开启或关闭保存信息
        /// </summary>
        private void tsmiSave_Click(object sender, EventArgs e)
        {
            saveData = !saveData;
            if (saveData)
            {
                tsmiSave.Text = "关闭保存";
            }
            else
            {
                tsmiSave.Text = "开启保存";
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}
